<?php

namespace common\models\c2\entity;

use backend\models\c2\entity\rbac\BeUser;
use common\helpers\Tool;
use dektrium\user\models\User;
use dektrium\user\traits\EventTrait;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

/**
 * This is the model class for table "{{%community}}".
 *
 * @property integer $id
 * @property integer $id2
 * @property string $name
 * @property string $area
 * @property string $address
 * @property integer $status
 * @property integer $cc_room_sum
 * @property integer $unit_sum
 * @property integer $wall_psum
 * @property integer $umber_start
 * @property integer $umber_end
 * @property string $umber_unit
 * @property integer $units
 * @property integer $total_floor
 * @property integer $th_per_floor
 * @property string $remarks
 * @property string $user_name
 * @property string $password
 * @property string $contact
 * @property string $phone
 */
class Community extends \cza\base\models\ActiveRecord
{

    public $province;
    public $city;
    public $district;


    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%community}}';
    }

    public function behaviors() {
        return [

        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'area', 'umber_unit', 'user_name', 'password'], 'required'],
            [['status', 'cc_room_sum', 'unit_sum', 'wall_psum', 'umber_start', 'umber_end', 'units', 'total_floor', 'th_per_floor', 'id2'], 'integer'],
            [['name', 'area', 'address', 'umber_unit', 'remarks', 'user_name', 'password', 'contact', 'phone'], 'string', 'max' => 255],
            'moblieNumberLength' => ['phone', 'match', 'pattern' => '/^1[0-9]{10}$/', 'message' => \Yii::t('app.c2', 'Must be mobile number')],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app.c2', 'ID'),
            'name' => Yii::t('app.c2', 'Name'),
            'area' => Yii::t('app.c2', 'Area'),
            'address' => Yii::t('app.c2', 'Address'),
            'status' => Yii::t('app.c2', 'Status'),
            'cc_room_sum' => Yii::t('app.c2', 'Cc Room Sum'),
            'unit_sum' => Yii::t('app.c2', 'Unit Sum'),
            'wall_psum' => Yii::t('app.c2', 'Wall Psum'),
            'umber_start' => Yii::t('app.c2', 'Umber Start'),
            'umber_end' => Yii::t('app.c2', 'Umber End'),
            'umber_unit' => Yii::t('app.c2', 'Umber Unit'),
            'units' => Yii::t('app.c2', 'Units'),
            'total_floor' => Yii::t('app.c2', 'Total Floor'),
            'th_per_floor' => Yii::t('app.c2', 'Th Per Floor'),
            'remarks' => Yii::t('app.c2', 'Remarks'),
            'user_name' => Yii::t('app.c2', 'User Name'),
            'password' => Yii::t('app.c2', 'Password'),
            'contact' => Yii::t('app.c2', 'Contact'),
            'phone' => Yii::t('app.c2', 'Phone'),
        ];
    }

    /**
     * @inheritdoc
     * @return \common\models\c2\query\CommunityQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\c2\query\CommunityQuery(get_called_class());
    }
    
    /**
    * setup default values
    **/
    public function loadDefaultValues($skipIfSet = true) {
        parent::loadDefaultValues($skipIfSet);
    }

    public function beforeSave($insert)
    {
        if ($this->isNewRecord && !Yii::$app->user->can('P_SYSTEM')) {
            Yii::$app->session->setFlash($this->getMessageName(), 'NO AUTH.');
            return false;
        }

        $data = [
            // 'id' => $this->id2,
            'name' => $this->name,
            'area' => $this->area,
            'address' => $this->address,
            'status' => (int) $this->status,
            'cc_room_sum' => (int) $this->cc_room_sum,
            'unit_sum' => (int) $this->unit_sum,
            'wall_psum' => (int) $this->wall_psum,
            'umber_start' => (int) $this->umber_start,
            'umber_end' => (int) $this->umber_end,
            'umber_unit' => $this->umber_unit,
            'units' => (int) $this->units,
            'total_floor' => (int) $this->total_floor,
            'th_per_floor' => (int) $this->th_per_floor,
            'remarks' => $this->remarks,
            'user_name' => $this->user_name,
            'password' => $this->password,
            'contact' => $this->contact,
            'phone' => $this->phone,
        ];

        if ($this->isNewRecord) {
            $url = \Yii::$app->params['api_url'] . '/api/Building/SetAddCommunity?supplier_id=' . Yii::$app->params['supplier_id'];
        } else {
            $data['id'] = $this->id2;
            $url = \Yii::$app->params['api_url'] . '/api/Building/SetUpdateCommunity?supplier_id=' . Yii::$app->params['supplier_id'];
        }

        // 同步到第三方平台
        $data = Json::encode($data);
        $result = Tool::curlPost($url, $data);
        Yii::info($result);

        $result = json_decode($result, true);
        if ($result['Status'] && $result['Status'] == 1) {
            if ($this->isNewRecord) {
                $this->id2 = $result['Ext'];
            }
            return parent::beforeSave($insert); // TODO: Change the autogenerated stub
        }
        Yii::$app->session->setFlash($this->getMessageName(), $result['Msg']);
        return false;



    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub

        if ($insert) {
            /** @var BeUser $user */
            $user = \Yii::createObject(['class'    => BeUser::className(), 'scenario' => 'create',]);
        } else {
            $user = BeUser::findOne(['community_id' => $this->id2]);
        }
        $user->community_id = $this->id2;
        $user->username = $this->user_name;
        $user->email = '';
        $user->password_hash = Yii::$app->security->generatePasswordHash($this->password);;
        $user->auth_key = Yii::$app->security->generateRandomString();
        $user->mobile_number = $this->phone;
        if (!$user->save()) {
            Yii::info($user->errors);
        }

    }

    public static function getHashMap($keyField, $valField, $condition = '')
    {
        if (!Yii::$app->user->can('P_SYSTEM')) {
            $condition = ['id2' => Yii::$app->user->getCommunityID()];
        }
        return parent::getHashMap($keyField, $valField, $condition); // TODO: Change the autogenerated stub
    }

    public static function getHashMap1($keyField, $valField, $condition = '') {
        $class = static::className();
        return ArrayHelper::map($class::find()->select([$keyField, $valField])->andWhere($condition)->asArray()->all(), $keyField, $valField);
    }

}
